import Request from '@/utils/luch-request/index.js'
import { api,env } from '@/config/config'
import Cache,{Keys} from '@/utils/cache.js'

const refreshRequest = new Request()
refreshRequest.setConfig((config) => { /* 设置全局配置 */
	config.baseURL = api.buyer /* 根域名不同 */
	return config
})

let lock = false
let promiseResult = []
export function getAccessToken() {
    return new Promise((resolve, reject) => {
    	promiseResult.push({
    		resolve,
    		reject
    	})
    	if (!lock) {
            lock = true
            refreshRequest.post('/passport/token', {
                refresh_token: uni.getStorageSync(Keys.refreshToken)
            },{
                header: {
                    uuid: uni.getStorageSync(Keys.uuid),
                    'content-type': 'application/x-www-form-urlencoded',
                },
            }).then(res => {
                //console.log('重新获取token')
                //console.log(res);
            	if (res.statusCode === 200) {
                    //console.log('重新存储到缓存中')
                    Cache.setItem(Keys.accessToken, res.data.accessToken);
                    Cache.setItem(Keys.refreshToken, res.data.refreshToken);
            	}
            	while (promiseResult.length) {
            		promiseResult.shift().resolve(res)
            	}
            	lock = false
            }).catch(err => {
            	while (promiseResult.length) {
            		// p1.reject(err)
            		promiseResult.shift().reject(err)
            	}
            	lock = false
            })
        }
    })
}